package com.xy.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //1.创建Shiro过滤工厂ShiroFilterFactoryBean，关联DefaultWebSecurityManager
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier(value = "getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器/设置访问页面需要那些权限
        /**
           anon：无需认证就可以访问
           authc：必须认证了才能访问
           user：必须拥有了  记住我 功能才能用
           perms：拥有对某个资源的权限才能访问
           role：拥有某个角色权限才能访问
         */
        Map<String,String> filterMap = new LinkedHashMap<>();
        //设置权限
//        filterMap.put("/user/update","authc");

        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置没有权限跳转登录页面的请求
        bean.setLoginUrl("/tologin");

        //正常情况下，没有权限就会跳转未授权页面，
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }


    //2.创建默认Web安全管理器,需要关联自定义的UserRealm
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier(value = "userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //1.创建  realm对象，需要自定义
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }


    //Shiro整合thymeleaf必须配置的bean
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
